package com.gh.controller.api;


import com.alibaba.fastjson.JSON;
import com.gh.common.result.R;
import com.gh.constant.MQConst;
import com.gh.dto.SmsDto;
import com.gh.hfb.RequestHelper;
import com.gh.service.MQService;
import com.gh.service.UserAccountService;
import com.gh.service.UserInfoService;
import com.gh.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Api(tags = "会员账户")
@RestController
@RequestMapping("/api/core/user-account")
@Slf4j
@RequiredArgsConstructor
public class UserAccountController {

    private final UserAccountService userAccountService;
    private final UserInfoService userInfoService;
    private final MQService mqService;

    @ApiOperation("会员充值")
    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(@ApiParam(value = "充值金额", required = true)
                          @PathVariable BigDecimal chargeAmt, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        //生成一个动态表单的字符串,用于远程提交
        String formStr = userAccountService.commitCharge(chargeAmt, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("会员充值异步回调")
    @PostMapping("/notify")
    public String notifyCharge(HttpServletRequest request) {
        //汇付宝向尚融宝发起回调携带的参数
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("账户充值异步回调参数如下：{}", JSON.toJSONString(paramMap));
        boolean signEquals = RequestHelper.isSignEquals(paramMap);
        if (!signEquals) {
            log.error("用户账户会员充值回调签名错误");
            return "fail";//随便都可以
        } else {
            if ("0001".equals(paramMap.get("resultCode"))) {
                log.info("验签成功，开始充值");
                String result = userAccountService.notifyCharge(paramMap);
                //发消息
                SmsDto smsDto = new SmsDto();
                String bindCode = request.getParameter("bindCode");
                String mobile = userInfoService.getMobileByBindCode(bindCode);
                smsDto.setMobile(mobile);
                smsDto.setMessage("充值成功");
                mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDto);
                return result;
            } else {
                return "success";//不要重试
            }
        }
    }

    @ApiOperation("用户提现")
    @PostMapping("/auth/commitWithdraw/{fetchAmt}")
    public R commitWithdraw(@ApiParam(value = "提现金额", required = true)
                            @PathVariable BigDecimal fetchAmt, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        //生成一个动态表单的字符串,用于远程提交
        String formStr = userAccountService.commitWithdraw(fetchAmt, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("用户提现异步回调")
    @PostMapping("/notifyWithdraw")
    public String notifyWithdraw(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        //校验签名
        if (RequestHelper.isSignEquals(paramMap)) {
            //提现成功交易
            if ("0001".equals(paramMap.get("resultCode"))) {
                String result = userAccountService.notifyWithdraw(paramMap);
                return result;
            } else {
                //提现异步回调失败
                return "fail";
            }
        } else {
            //
            log.info("提现异步签名错误:{}", JSON.toJSONString(paramMap));
            return "fail";
        }
    }
}

